﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using PowerAwareBluetooth.Controller.IO;

namespace PowerAwareBluetooth.Controller.AI
{
    public class CellTowerLearner
    {
        public enum BluetoothInCell
        {
            NEVER = 1,
            SPARSELY = 2,
            SOMETIMES = 4,
            ALOT = 5
        }

        private Dictionary<string, StateMachine> m_cells;

        public CellTowerLearner()
        {
            m_cells = IOManager.Load(IOManager.SaveType.CELL_TOWER_INFO) as Dictionary<string, StateMachine>;
            if (m_cells == null)
            {
                m_cells = new Dictionary<string, StateMachine>();
            }
        }

        /// <summary>
        /// get the learnt status of relevant bluetooth devices in the given cell
        /// </summary>
        /// <param name="cellId"></param>
        /// <returns></returns>
        public BluetoothInCell BluetoothStatusInCell(string cellId)
        {
            StateMachine sm;
            if (!m_cells.TryGetValue(cellId, out sm))
            {
                return BluetoothInCell.SPARSELY;
            }

            switch (sm.CurrentState)
            {
                case StateMachine.States.OFF_HARD: return BluetoothInCell.NEVER;
                case StateMachine.States.OFF: return BluetoothInCell.SPARSELY;
                case StateMachine.States.ON: return BluetoothInCell.SOMETIMES;
                case StateMachine.States.ON_HARD: return BluetoothInCell.ALOT;
                default: return BluetoothInCell.SPARSELY;
            }
        }

        /// <summary>
        /// Learn the relevant bluetooth devices status in the given cell
        /// </summary>
        /// <param name="cellId">cell name </param>
        /// <param name="bluetoothFound">were relevant bluetooth devices found</param>
        public void LearnBluetoothStatusInCell(string cellId, bool bluetoothFound)
        {
            StateMachine sm;
            if (!m_cells.TryGetValue(cellId, out sm))
            {
                //first time we see this cell. ignore the reported result and just add to dictionary
                sm = new StateMachine();
                m_cells.Add(cellId, sm);
            }
            else
            {
                //not the first time we see the cell. change its stateMachine according to what we learnt

                if (bluetoothFound)
                {
                    sm.IncrementState();
                }
                else
                {
                    sm.DecrementState();
                }
            }
            

            // save to hard disk
            IOManager.Save(m_cells, IOManager.SaveType.CELL_TOWER_INFO);
        }
    }
}
